package edu.ecust.design.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.ecust.design.cons.AccountContext;
import edu.ecust.design.domain.Account;
import edu.ecust.design.service.IAccountService;

/**
 * 系统登录
 * 
 * @author xiefei
 * 
 */
@Controller
@RequestMapping("/account")
public class LoginController extends BaseController {
	private static final Logger logger = Logger
			.getLogger(LoginController.class);
	@Autowired
	private IAccountService accountService;

	@Override
	public String init() {
		return "LoginPage";
	}

	/**
	 * 系统登录 成功后将Account对象放置到session中
	 * 
	 * @param request
	 * @param response
	 * @param userName
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/login")
	public String logon(HttpServletRequest request,
			HttpServletResponse response, String userName, String password) {
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		map.put("success", false);
		if (StringUtils.isNotEmpty(userName)
				&& StringUtils.isNotEmpty(password)) {
			Account acc = accountService.checkAccount(userName, password);
			if (acc != null) {
				request.getSession().setAttribute(
						AccountContext.session.getText(), acc);
				map.put("success", true);
			}
		} else {
			logger.error("用户名，密码为空，登录失败");
			throw new IllegalArgumentException();
		}
		return this.write(map);
	}

	/**
	 * 系统登出
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) {
		Account acc = getSessionAccount(request);
		if (acc != null) {
			setSessionAccount(request, null);
		}
		if (request.getSession() != null) {
			request.getSession().invalidate();
		}
		return "LoginPage";
	}
}
